import service from '@/api/request'
import CrudPage from './CrudPage.vue'
import type { FormData, SearchParams } from './page.type'
import type { Component } from 'vue'
import { defineComponent, h } from 'vue'

export interface CrudConfig {
  page: {
    title: string
    description?: string
    permission?: string
    targetNameField?: string
  }
  api: {
    GET_URL: string
    CREATE_URL: string
    UPDATE_URL: string
    DELETE_URL: string
    BATCH_DELETE_URL: string
  }
  search: {
    fields: any[]
  }
  tableColumns: any[]
  tableActionColumn: {
    width: string
    align: string
    fixed: string
  }
  tableActions: any[]
  form: {
    fields: any[]
    rules: any
    labelWidth?: string
    dialogWidth?: string
    addTitle?: string
    editTitle?: string
  }
  actions: {
    add?: {
      text: string
      icon?: string
      permission?: string
    }
    batchDelete?: {
      text: string
      icon?: string
      permission?: string
    }
  }
  pagination: {
    pageSizes: number[]
    defaultPageSize: number
  }
  messages?: {
    loadSuccess?: string
    addSuccess?: string
    editSuccess?: string
  }
}

/**
 * 创建 API 对象
 */
function createApi(apiConfig: CrudConfig['api']) {
  return {
    getList: (page: number, size: number, params?: SearchParams) =>
      service.get(apiConfig.GET_URL, { params: { current: page, size, ...params } }),
    create: (data: FormData) => service.post(apiConfig.CREATE_URL, data),
    update: (data: FormData) => {
      const id = data.id as string
      const dataToSend = { ...data }
      delete dataToSend.id
      delete dataToSend.createdAt
      delete dataToSend.updatedAt
      return service.put(apiConfig.UPDATE_URL + `/${id}`, dataToSend)
    },
    delete: (id: string) => service.delete(apiConfig.DELETE_URL + `/${id}`),
    batchDelete: (ids: string[]) => service.delete(apiConfig.BATCH_DELETE_URL, { data: ids }),
  }
}

/**
 * 工厂函数 - 创建CRUD页面
 * @param config 配置
 * @returns Vue组件
 */
export function createCrudPage(config: CrudConfig): Component {
  return defineComponent({
    name: 'CrudPageWrapper',
    components: { CrudPage },
    setup() {
      // 创建API对象
      const api = createApi(config.api)

      // 渲染函数版本，避免内联模板问题
      return () => {
        return h(CrudPage, {
          config,
          api,
        })
      }
    },
  })
}
